package yki.paperplane.server.servlet.user;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;

import yki.paperplane.server.db.useroperator.ModifyNameOperator;
import yki.paperplane.server.servlet.BaseServlet;
import yki.paperplane.server.servlet.StatusCode;
import yki.paperplane.server.utils.XMLUtils;

public class ModifyNameRequestServlet extends BaseServlet {

	public ModifyNameRequestServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Date date = new Date(System.currentTimeMillis());
		Time time = new Time(System.currentTimeMillis());
		response.getWriter().println(
				"Hello, this is PaperPlaneServer ModifyNameRequestServlet! "
						+ date.toString() + " " + time.toString());
		response.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Date date = new Date(System.currentTimeMillis());
		Time time = new Time(System.currentTimeMillis());

		try {
			Map<String, String> map = XMLUtils.parseXML(
					request.getInputStream()).get(0);

			Connection connection = getDBConnection();

			int user_id = Integer.valueOf(map.get(XMLUtils.TAG_USER_ID));
			String password = map.get(XMLUtils.TAG_PASSWORD);
			System.out.println("Connected to " + user_id + "; " + password);
			int id = getUserID(connection, user_id, password);

			if (id != user_id) {
				response.addHeader(STATUSCODE,
						StatusCode.STATUS_INCORRECT_PASSWORD + "");
				return;
			}

			String new_name = map.get("name");
			System.out.println(new_name);

			ModifyNameOperator operator = new ModifyNameOperator(user_id,
					new_name);
			int result = operator.execute(connection);
			if (result < 0) {
				response.addHeader(STATUSCODE, StatusCode.STATUS_SERVER_ERROR
						+ "");
				return;
			}
			response.addHeader(STATUSCODE, "" + StatusCode.STATUS_SUCCESS);
			connection.close();
			response.flushBuffer();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("end " + date.toString() + " " + time.toString());
	}

}
